<template>
  <n-form :model="form" :rules="rules" ref="formRef" size="large">
    <n-form-item-row label="用户名" path="username">
      <n-input placeholder="请输入用户名" v-model:value="form.username"/>
    </n-form-item-row>
    <n-form-item-row label="密码" path="password">
      <n-input type="password" placeholder="请输入密码" v-model:value="form.password"/>
    </n-form-item-row>
    <n-form-item-row label="重复密码" path="againPassword">
      <n-input type="password" :disabled="!form.password" placeholder="请输入密码"
               v-model:value="form.againPassword" @keydown.enter.prevent="handleRegister"/>
    </n-form-item-row>
  </n-form>
  <n-button type="primary" block secondary strong @click="handleRegister">
    注册
  </n-button>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {FormItemRule} from "naive-ui";
import api from '@/api'
import {encrypt} from "@/utils";


const form = ref({
  username: '',
  password: '',
  againPassword: '',
})
const formRef = ref()
const rules = ref({
  username: [{
    required: true,
    message: '请输入用户名',
    trigger: ['input']
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['input']
  }, {
    validator: validatePasswordStartWith,
    message: '两次密码输入不一致',
    trigger: 'input'
  }],
  againPassword: [{
    required: true,
    message: '请再次输入密码',
    trigger: ['input']
  }, {
    validator: validatePasswordSame,
    message: '两次密码输入不一致',
    trigger: 'input'
  }]
})
const handleRegister = () => {
  formRef.value.validate((error: any) => {
    if (!error) {
      // formRegister.value.password = encrypt(formRegister.value.password)
      // formRegister.value.againPassword = encrypt(formRegister.value.againPassword)
      api.auth.register({
        username: form.value.username,
        password: encrypt(form.value.password)
      }).then((res: any)=>{
        if(res.data.code===0){
          window.$message.success(res.data.msg)

        }
      })
    }
  })
}

function validatePasswordStartWith(
    rule: FormItemRule,
    value: string
): boolean {
  return (
      !!form.value.password &&
      form.value.password.startsWith(value) &&
      form.value.password.length >= value.length
  )
}

function validatePasswordSame(rule: FormItemRule, value: string): boolean {
  return value === form.value.password
}

</script>

<style scoped>

</style>
